package com.yuanfengPlus.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {

    // Excel导入方法
    public static <T> List<T> importExcel(MultipartFile file, Class<T> clazz) {
        List<T> dataList = new ArrayList<>();
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, clazz, new PageReadListener<T>(dataList1 -> dataList.addAll(dataList1))).sheet().doRead();
            return dataList;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Excel导入失败");
        }
    }

    // Excel导出方法
    public static void exportExcel(List<?> dataList, String fileName, HttpServletResponse response, Class<?> clazz) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 防止中文乱码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");
            OutputStream outputStream = response.getOutputStream();
            ExcelWriter excelWriter = EasyExcel.write(outputStream, clazz).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").build();
            excelWriter.write(dataList, writeSheet);
            excelWriter.finish();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Excel导出失败");
        }
    }
}
   